package com.wr.hangzhounewlight.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wr.hangzhounewlight.mapper.SiloRawMaterialMapMapper;
import com.wr.hangzhounewlight.obj.api.silorawmaterialmappingissue.SiloRawMaterialMappingIssueRequest;
import com.wr.hangzhounewlight.obj.api.silorawmaterialmappingissue.SiloRawMaterialMappingIssueRequest.SiloMaterialSetDTO;
import com.wr.hangzhounewlight.obj.api.silorawmaterialmappingissue.SiloRawMaterialMappingIssueResponse;
import com.wr.hangzhounewlight.obj.database.SiloRawMaterialMapEntity;
import com.wr.hangzhounewlight.opcua.OpcUaClientManager;
import com.wr.hangzhounewlight.opcua.OpcUaUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.stream.IntStream;

/**
 * @author yuanzhizhuo
 * createDate 2025/10/23
 */
@Slf4j
@Service
public class SiloRawMaterialMappingIssueService {

    private final SiloRawMaterialMapMapper mapper;
    private final OpcUaClientManager opcUaClientManager;
    private final String opcUaUrl = "opc.tcp://frp-fog.com:48347";
    private static final Map<String, String> workshopMap = new HashMap<>();
    private static final Map<String, String> T = new HashMap<>();

    static {
        workshopMap.put("农膜", "NongMo");
        workshopMap.put("吹膜", "ChuiMo");
        workshopMap.put("包材", "BaoCai");
    }

    static {
        IntStream.rangeClosed(1, 60).forEach(i -> T.put("主料" + i, "RawName_" + String.format("%03d", i)));
    }

    public SiloRawMaterialMappingIssueService(
            SiloRawMaterialMapMapper mapper, OpcUaClientManager opcUaClientManager
    ) {
        this.mapper = mapper;
        this.opcUaClientManager = opcUaClientManager;
    }

    /**
     * 料仓料品对照表下发
     *
     * @param request dto
     * @return 是否下发成功
     */
    public SiloRawMaterialMappingIssueResponse siloRawMaterialMappingIssue(
            SiloRawMaterialMappingIssueRequest request
    ) {
        try {
            saveToDB(request);
            log.info("料仓料品, 对照表保存到数据库成功");
        } catch (Exception e) {
            log.error("料仓料品, 对照表保存到数据库失败", e);
            return new SiloRawMaterialMappingIssueResponse(0, "料仓料品, 对照表保存到数据库失败");
        }
        try {
            saveToNode(request);
            log.info("料仓料品, 对照表保存到节点成功");
        } catch (Exception e) {
            log.error("料仓料品, 对照表保存到节点失败", e);
            return new SiloRawMaterialMappingIssueResponse(0, "料仓料品, 对照表保存到节点失败");
        }
        return new SiloRawMaterialMappingIssueResponse(1, "料仓料品, 对照表下发成功");
    }

    /**
     * 保存料仓料品对照表到数据库
     *
     * @param request dto
     * @throws RuntimeException 保存到数据库失败
     */
    private void saveToDB(SiloRawMaterialMappingIssueRequest request) throws RuntimeException {
        String workshopCH = request.getWorkshop();
        resetWorkshopSiloRawMaterialMapping(workshopCH);
        for (SiloMaterialSetDTO siloMaterialSetDTO : request.getSiloMaterialSet()) {
            mapper.insert(new SiloRawMaterialMapEntity(workshopCH, siloMaterialSetDTO));
        }
    }

    /**
     * 重置车间的料仓料品对照表
     *
     * @param workshopCH 车间名称
     */
    private void resetWorkshopSiloRawMaterialMapping(String workshopCH) throws RuntimeException {
        log.info("料仓料品, 正在重置{}车间的料仓料品对照表", workshopCH);
        LambdaUpdateWrapper<SiloRawMaterialMapEntity> updateWrapper = new LambdaUpdateWrapper<SiloRawMaterialMapEntity>()
                .eq(SiloRawMaterialMapEntity::getWorkshop, workshopCH);
        mapper.delete(updateWrapper);
    }

    /**
     * 保存料仓料品对照表到节点
     * <p>
     * 模糊匹配所有new NodeId(0, 53722)下的节点
     * 忽略机台, 匹配节点identifier中包含车间名称和料仓名称的节点
     *
     * @param request dto
     * @throws RuntimeException 保存到节点失败
     */
    private void saveToNode(SiloRawMaterialMappingIssueRequest request) throws RuntimeException, UaException, ExecutionException, InterruptedException, TimeoutException {
        Optional<OpcUaClient> opcUaClientOptional = opcUaClientManager.getOpcUaClient(opcUaUrl);
        if (opcUaClientOptional.isPresent()) {
            OpcUaClient opcUaClient = opcUaClientOptional.get();
            String workshopCH = request.getWorkshop();
            List<NodeId> nodeIdList = OpcUaUtil.browseNode(opcUaClient, new NodeId(0, 53722));
            for (SiloMaterialSetDTO siloMaterial : request.getSiloMaterialSet()) {
                String workshopNodeKeyword = SiloRawMaterialMappingIssueService.workshopMap.get(workshopCH);
                String siloKeyWord = T.get(siloMaterial.getSilo());
                List<NodeId> workshopSiloNodeList = matchNodeId(nodeIdList, workshopNodeKeyword, siloKeyWord);
                for (NodeId nodeId : workshopSiloNodeList) {
                    try {
                        log.info("正在写入节点值, nodeId: {}, value: {}", nodeId, siloMaterial.getRawMaterialName());
                        OpcUaUtil.writeValue(opcUaClient, nodeId, siloMaterial.getRawMaterialName());
                    } catch (UaException e) {
                        log.error("写入节点值失败, nodeId: {}", nodeId, e);
                    }
                }
            }
        }
    }

    /**
     * 匹配节点
     * <p>
     * 节点标识符中包含车间名称和料罐编号的
     *
     * @param nodeIdList          节点列表
     * @param workshopNodeKeyword 车间节点关键字
     * @param nodeKeyWord         料仓节点关键字
     * @return 匹配的节点列表
     */
    private static List<NodeId> matchNodeId(
            List<NodeId> nodeIdList, String workshopNodeKeyword, String nodeKeyWord
    ) {
        return nodeIdList.stream()
                .filter(nodeId -> String.valueOf(nodeId.getIdentifier()).contains(workshopNodeKeyword))
                .filter(nodeId -> String.valueOf(nodeId.getIdentifier()).contains(nodeKeyWord))
                .toList();
    }

}
